package ru.reaperoq.taskmanager.controllers

import jakarta.servlet.http.HttpServletRequest
import org.springframework.beans.factory.annotation.Qualifier
import org.springframework.web.bind.annotation.*
import ru.reaperoq.taskmanager.dto.AddListRequest
import ru.reaperoq.taskmanager.dto.ListResponse
import ru.reaperoq.taskmanager.dto.Response
import ru.reaperoq.taskmanager.getUser
import ru.reaperoq.taskmanager.models.TaskList
import ru.reaperoq.taskmanager.repositories.ListRepository
import ru.reaperoq.taskmanager.repositories.UserRepository
import ru.reaperoq.taskmanager.services.JwtService
import ru.reaperoq.taskmanager.toEpoch

@RestController
@RequestMapping("/api/lists")
class ListController(
    private val listRepository: ListRepository,
    private val userRepository: UserRepository,
    private val jwtService: JwtService
) {
    @PostMapping("/create")
    fun createList(@RequestBody addListRequest: AddListRequest, req: HttpServletRequest) : Response<ListResponse> {
        val user = req.getUser(userRepository, jwtService)
        return Response.success(
            listRepository.save(
                TaskList(
                    title = addListRequest.title,
                    author = user
                )
            ).toResponse()
        )
    }

    @GetMapping("/")

    private fun TaskList.toResponse() : ListResponse =
        ListResponse(
            id = this.id!!,
            title = this.title,
            createdAt = this.createdAt.toEpoch(),
            authorId = this.author.id!!,
            sharedId = this.sharedId?.toString(),
            tasks = tasks.map { it.toResponse() }
        )
}